﻿using Abp.Application.Services;
using Abp.Domain.Repositories;
using Batman.Cache;
using Batman.Cache.Attributes;
using Batman.Cms.Core.Const;
using Batman.Cms.Core.Models.Mvc;
using Batman.Core;
using Batman.Jianbei.Forum.Core.ChatRoom;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Batman.Jianbei.Forum.Services.ChatRoom
{
    public class MaskService : ApplicationService, ICacheWorkable
    {
        public IRepository<Mask, string> repo { get; set; }

        [Cacher(CacherType = CacherType.Clean, TargetId = CacheNames.Masks)]
        public virtual bool SetDeleted(string maskId, bool isDeleted)
        {
            repo.Update(maskId, t => t.IsDeleted = isDeleted);
            return true;
        }

        /// <summary>
        ///  批量禁用
        /// </summary>
        /// <param name="maskIds"></param>
        /// <returns></returns>
        [Cacher(CacherType = CacherType.Clean, TargetId = CacheNames.Masks)]
        public virtual bool SetDeleted(List<string> maskIds)
        {
            maskIds.ForEach(maskId => repo.Update(maskId, t => t.IsDeleted = true));
            return true;
        }

        /// <summary>
        ///  批量启用
        /// </summary>
        /// <param name="maskIds"></param>
        /// <returns></returns>
        [Cacher(CacherType = CacherType.Clean, TargetId = CacheNames.Masks)]
        public virtual bool SetUnDeleted(List<string> maskIds)
        {
            maskIds.ForEach(maskId => repo.Update(maskId, t => t.IsDeleted = false));
            return true;
        }

        [Cacher(CacherType = CacherType.Clean, TargetId = CacheNames.Masks)]
        public virtual ResponseBase Save(Mask mask)
        {
            mask.Nickname = mask.Nickname.Trim();
            var exist = repo.GetQuery().Any(t => t.Nickname == mask.Nickname);

            if (exist) return new ResponseBase(false, "昵称已存在");
            mask.CreateAt = DateTime.Now;

            repo.InsertOrUpdate(mask);
            return new ResponseBase();
        }

        /// <summary>
        /// 更新匿名身份
        /// </summary>
        /// <param name="mask"></param>
        /// <returns></returns>
        [Cacher(CacherType = CacherType.Clean, TargetId = CacheNames.Masks)]
        public virtual ResponseBase Update(Mask mask)
        {
            var existing = repo.GetQuery().Where(t => t.Id == mask.Id).FirstOrDefault();
            if (existing == null) return new ResponseBase(false, "非法请求:匿名身份不存在");

            mask.Nickname = mask.Nickname.Trim();
            var exist = repo.GetQuery().Any(t => t.Nickname == mask.Nickname && t.Id != mask.Id);

            if (exist) return new ResponseBase(false, "昵称已存在");

            existing.Nickname = mask.Nickname;
            existing.AvatarId = mask.AvatarId;
            repo.Update(mask);
            return new ResponseBase();
        }
    }
}
